trigger NewAccountShare on Purchase_Object__c (after insert, after update) {
   Set<Id> AcId = New Set<Id>();
    list<AccountShare> ASlist = new list<AccountShare>();
    list<AccountShare> ASlist1 = new list<AccountShare>();
    list<AccountTeamMember> ATeam = new list<AccountTeamMember>();
    list<ID> ATeam1 = new list<Id>();
    list<Purchase_Object__Share> POSlist = new list<Purchase_Object__Share>();
    list<Purchase_Object__Share> POSlist1 = [select id,parentid,USERORGROUPID from Purchase_Object__Share];
    list<Purchase_Object__Share> POSlistdel = new list<Purchase_Object__Share>();
    list<Account> acclist = new list<Account>();
    list<Account> ATlist = new list<Account>();
     for(Purchase_Object__c poObj : Trigger.New){
        AcId.add(poObj.Account__c);
      }
    ASlist = [select ID,ACCOUNTID,USERORGROUPID,ACCOUNTACCESSLEVEL from AccountShare where RowCause != 'Team' AND ACCOUNTID IN : AcId];
    System.debug('AS Group List' + ASlist);
    ATeam = [Select ACCOUNTID,UserID from AccountTeamMember where TeamMemberRole = 'Account Manager' AND ACCOUNTID IN : AcId];
    System.Debug('AT UserList' + ATeam );
    for(AccountTeamMember Atm :ATeam){
      ATeam1.add(Atm.UserId);
      }
    ASlist1 = [Select Id,ACCOUNTID,USERORGROUPID from AccountShare where USERORGROUPID IN: ATeam1];
    if(trigger.isupdate)
    {
        for(Purchase_Object__c po : trigger.new)
        {
            for(Purchase_Object__Share poshare :POSlist1)
            {
                if(po.id == poshare.parentid && po.Ownerid!=poshare.USERORGROUPID)
                {
                    POSlistdel.add(poshare);
                }
            }
        }
    }
   delete POSlistdel; 
   for(Purchase_Object__c po : trigger.new)
    {
        for(AccountShare as1: ASlist1)
        {
            if(po.Account__c == as1.ACCOUNTID && as1.USERORGROUPID!=po.Ownerid)
            {
                Purchase_Object__Share pos = new Purchase_Object__Share();
                pos.ACCESSLEVEL= 'read' ;
                pos.USERORGROUPID= as1.USERORGROUPID;
                pos.PARENTID= po.id;
                POSlist.add(pos);
                system.debug('UserID'+as1.USERORGROUPID);
                system.debug('Parentid'+po.id);
            }
        }
    }
    for(Purchase_Object__c po : trigger.new)
    {
        for(AccountShare as1: ASlist)
        {
            if(po.Account__c == as1.ACCOUNTID && as1.USERORGROUPID!=po.Ownerid)
            {
                Purchase_Object__Share pos = new Purchase_Object__Share();
                pos.ACCESSLEVEL= 'read' ;
                pos.USERORGROUPID= as1.USERORGROUPID;
                pos.PARENTID= po.id;
                POSlist.add(pos);
                system.debug('User ID'+as1.USERORGROUPID);
                system.debug('Parentid'+po.id);
            }
        }
      }         
    insert POSlist;             
}